import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getStorage } from '@/utils/storage'

NProgress.configure({ showSpinner: false });

const whiteList = ['/']

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const hasToken = getStorage('token')
    if (hasToken) {
        const hasRoles = store.getters.roles && store.getters.roles.length > 0
        if (hasRoles) {
            next()
        } else {
            try {
                // 重新刷新用户信息获得路由权限
                const { roles } = await store.dispatch('getInfo')
                // 在本地路由表中找出对应的权限路由
                const accessRoutes = await store.dispatch('generateRoutes', roles)
                router.addRoutes(accessRoutes)
                next({ ...to, replace: true }) // 确保addRoutes已完成 防止刷新之后页面空白
            } catch (error) {
                // remove token and go to login page to re-login
                await store.dispatch('removeToken')
                Message.error(error || 'Has Error')
                next(`/?redirect=${to.path}`)
                NProgress.done()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach((to) => {
    let current = ''
    if (to.path.includes('form') || to.path.includes('dashboard')) {
        current = to.path
    } else {
        current = to.path.split('/')[to.path.split('/').length - 1]
    }
    store.dispatch('setCurrentMenu', current)
    NProgress.done()
})